package com.lowca.news.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.util.Assert;

import static com.lowca.news.constant.Constants.CAPTCHA_CONTEXT;

public class Captchas {

	private Captchas() {
	}

	/**
	 * <p>查看验证码是否正确，此方法不会删除当前验证码。</p>
	 * <p>请注意：这个方法仅仅用于ajax预先检验验证码的场合。</p>
	 * 
	 * @param request
	 * @param captchaValue
	 * @return
	 */
	public static boolean look(HttpServletRequest request, String captchaValue) {
		return compare(request, captchaValue, false);
	}

	/**
	 * 核对验证码是否正确，这个方法会删除掉当前验证码，确保1个验证码只能使用一次
	 * 
	 * @param request
	 * @param captchaValue
	 * @return
	 */
	public static boolean check(HttpServletRequest request, String captchaValue) {
		return compare(request, captchaValue, true);
	}

	private static boolean compare(HttpServletRequest request,
			String captchaValue, boolean deleteIt) {
		Assert.notNull(request, "request not be null");
		Assert.hasText(captchaValue, "captcha can not be empty");
		HttpSession session = request.getSession();
		Object captchaInSession = session.getAttribute(CAPTCHA_CONTEXT);
		if (captchaInSession != null
				&& captchaInSession.toString().equalsIgnoreCase(captchaValue)) {
			if (deleteIt) {
				session.removeAttribute(CAPTCHA_CONTEXT);
			}
			return true;
		}
		if (deleteIt) {
			session.removeAttribute(CAPTCHA_CONTEXT);
		}
		return false;
	}

}
